import 'dart:async';

import 'package:flutter/material.dart';
import 'package:p_location/common/constant/color_list.dart';
import 'package:p_location/common/constant/sp_key.dart';
import 'package:p_location/common/res/common_res.dart';
import 'package:p_location/home/constant/home_http_url.dart';
import 'package:p_location/home/module_menus/work_desk_menus.dart';
import 'package:p_location/home/obj/home_person_summary_info.dart';
import 'package:p_location/home/res/res_home_person_summary.dart';
import 'package:p_location/home/widget/home_tab_area_info_widget.dart';
import 'package:p_location/home/widget/hometab_alarm_widget.dart';
import 'package:p_location/home/widget/loading_container.dart';
import 'package:p_location/net/dio_http_client.dart';
import 'package:p_location/net/net_listener_impl.dart';
import 'package:p_location/user/constants/user_http_url.dart';
import 'package:p_location/user/obj/user_info.dart';
import 'package:p_location/user/res/building.dart';
import 'package:p_location/user/res/module_info.dart';
import 'package:p_location/user/res/res_license_info.dart';
import 'package:p_location/user/ui/login_page.dart';
import 'package:p_location/utils/shared_preferences_util.dart';
import 'package:p_location/utils/toast_util.dart';
import 'package:package_info/package_info.dart';

import '../home.dart';

class TestDeskTab extends StatefulWidget {
  @override
  State<StatefulWidget> createState() {
    return _TestDeskTabState();
  }
}

class _TestDeskTabState extends State<TestDeskTab> with WidgetsBindingObserver {
  bool _loading = false;
  double appBarAlpha = 0;
  int taskTotalNum;
  int messageInfoCount;

  HomePersonSummaryInfo _homePersonSummaryInfo;

  String _accountName = "";
  String _buildName = "";

  String _versionCode;
  String _versionName = '获取中...';

  Timer _summaryTimer;
  int summaryInterval = 5;

  bool isResumed = true;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addObserver(this);
    initCacheLoginInfo();
    initCacheBuildInfo();
    getVersionName();
    _handleRefresh();
    timerRunnable();
  }

  @override
  void deactivate() {
    super.deactivate();
  }

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    super.dispose();
    print("mydispose");
    _summaryTimer?.cancel();
//    _cancelToken.cancel("cancelled");
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    switch (state) {
      case AppLifecycleState.resumed:
        print('应用程序可见并响应用户输入。');
        isResumed = true;
        break;
      case AppLifecycleState.inactive:
        print('应用程序处于非活动状态，并且未接收用户输入');
        break;
      case AppLifecycleState.paused:
        print('用户当前看不到应用程序，没有响应');
        isResumed = false;
        break;
//      case AppLifecycleState.suspending:
//        print('应用程序将暂停。');
//        break;
      default:
    }
  }

  @override
  Widget build(BuildContext context) {
    print('Widget build Homepage');
    return Scaffold(
      appBar: AppBar(
        title: Text(
          "首页",
          style: TextStyle(color: Colors.black),
        ),
        centerTitle: true,
        backgroundColor: Colors.white,
        leading: Builder(
          //https://blog.csdn.net/qq_42181602/article/details/100763989
          builder: (context) {
            return IconButton(
              icon: Icon(Icons.menu),
              color: Colors.black,
              onPressed: () {
                Scaffold.of(context).openDrawer();
              },
            );
          },
        ),
      ),
      drawer: _drawer,
      body: LoadingContainer(
        isLoading: _loading,
        child: Stack(
          children: <Widget>[
            MediaQuery.removePadding(
                removeTop: true,
                context: context,
                child: RefreshIndicator(
                    onRefresh: _handleRefresh,
                    child: NotificationListener(
                        onNotification: (scrollNotification) {
                          if (scrollNotification is ScrollUpdateNotification &&
                              scrollNotification.depth == 0) {
                            //滚动且是列表滚动的时候
//                            _onScroll(scrollNotification.metrics.pixels);
                          }
                          return false;
                        },
                        child: _listView))),
//            _appBar
          ],
        ),
      ),
      backgroundColor: Color(0xfff6f6f6),
    );
  }

  Widget get _listView {
    return ListView(
      children: <Widget>[
        Stack(
          children: <Widget>[
            Container(
              child: Column(
                children: [
                  FractionallySizedBox(
                      widthFactor: 1,
                      child: Container(
                          margin: EdgeInsets.fromLTRB(12, 12, 12, 0),
                          child: Container(
                            decoration: BoxDecoration(
                                image: DecorationImage(
                                    image: ExactAssetImage(
                                        'images/bg_border_blue.png'),
                                    fit: BoxFit.fill),
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5))),
//                            padding: EdgeInsets.all(12),
                            child: Column(
                              crossAxisAlignment: CrossAxisAlignment.start,
                              children: [
                                Container(
                                  margin: EdgeInsets.fromLTRB(16, 10, 10, 5),
                                  child: Text(
                                    getConcreteSummary("当前在线人员"),
                                    style: TextStyle(
                                        color: Colors.white,
                                        fontSize: 36,
                                        fontWeight: FontWeight.bold),
                                  ),
                                ),
                                Container(
                                  margin: EdgeInsets.fromLTRB(16, 0, 10, 10),
                                  child: Text("当前在线人员",
                                      style: TextStyle(
                                          color: Colors.white, fontSize: 20)),
                                )
                              ],
                            ),
                          ))),
                  Container(
                    margin: EdgeInsets.all(12),
//                    color: Colors.yellow,
                    child: GridView.builder(
                        shrinkWrap: true,
                        physics: new NeverScrollableScrollPhysics(),
                        //禁用滑动事件
                        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                            crossAxisCount: 2,
                            mainAxisSpacing: 10,
                            crossAxisSpacing: 10,
                            childAspectRatio: 2.3),
                        itemCount: WorkDeskMenus.menus.length,
                        itemBuilder: (context, index) {
                          return Container(
                            padding: EdgeInsets.only(left: 10, right: 10),
                            decoration: BoxDecoration(
                                borderRadius:
                                    BorderRadius.all(Radius.circular(5)),
                                color: Colors.white),
                            child: Row(
                              children: [
                                Image.asset(
                                  WorkDeskMenus.menus[index].icon,
                                  width: 40,
                                  height: 40,
                                ),
                                Container(
                                    margin: EdgeInsets.only(left: 10),
                                    child: Column(
                                      mainAxisAlignment:
                                          MainAxisAlignment.center,
                                      crossAxisAlignment:
                                          CrossAxisAlignment.start,
                                      children: [
                                        Text(getConcreteSummary(
                                            WorkDeskMenus.menus[index].title)),
                                        Text(
                                          WorkDeskMenus.menus[index].title,
                                          style: TextStyle(
                                              color: ColorList.BLACK_65,
                                              fontSize: 14),
                                        )
                                      ],
                                    ))
                              ],
                            ),
                          );
                        }),
                  ),
                  HomeTabAreaInfoWidget(key: areaInfoKey),
                  HomeTabAlarmWidget(key: alarmInfoKey)
                ],
              ),
            )
          ],
        )
      ],
    );
  }

  Future<bool> _handleRefresh() async {
    if (isResumed) {
      await getSummaryInfo();
      await areaInfoKey.currentState.refresh();
      await alarmInfoKey.currentState.refresh();
    }
    return true;
  }

  getSummaryInfo() async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        HomeHttpUrl.HOME_PERSON_SUMMARY_INFO,
        params,
        NetListenerImpl((response) {
          setState(() {
            if (response != null && response.data != null) {
              ResHomePersonSummary res =
                  ResHomePersonSummary.fromJson(response.data);
              if (res != null && res.data != null) {
                _homePersonSummaryInfo = res.data;
              }
            }
          });
        }, (errorRes) {}));
  }

  getConcreteSummary(key) {
    if (_homePersonSummaryInfo != null) {
      if (key == "内部员工") {
        return '${_homePersonSummaryInfo.inSideStuffNum}';
      } else if (key == "外来人员") {
        return '${_homePersonSummaryInfo.outSideVisitorNum}';
      } else if (key == "承包商") {
        return '${_homePersonSummaryInfo.contractorNum}';
      } else if (key == "内部/外部车辆") {
        return '${_homePersonSummaryInfo.inSideCarNum}/${_homePersonSummaryInfo.outSideCarNum}';
      } else if (key == "当前在线人员") {
        var sum = _homePersonSummaryInfo.inSideStuffNum +
                _homePersonSummaryInfo.outSideVisitorNum +
                _homePersonSummaryInfo
                    .contractorNum /*+
            _homePersonSummaryInfo.inSideCarNum +
            _homePersonSummaryInfo.outSideCarNum*/
            ;
        return '$sum';
      }
    }
    return "-";
  }

  get _drawer => Drawer(
          child: Container(
        child: Stack(
          children: [
            ListView(children: [
              DrawerHeader(
                decoration: BoxDecoration(
                  color: Colors.lightBlueAccent,
                ),
                child: Center(
                  child: Container(
                    alignment: Alignment.center,
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        ClipOval(child: Image.asset(
                          'images/logo.png',
                          width: 70,
                          height: 70,
                          fit: BoxFit.cover,
                        ),),
                        Padding(
                          padding: EdgeInsets.only(top: 10),
                          child: Text(
                              _accountName,style: TextStyle(
                            color: Colors.white
                          ),
                          ),
                        )
                      ],
                    ),
                  ),
                ),
              ),
              GestureDetector(
                behavior: HitTestBehavior.opaque,
                onTap: () {
//                  showBottomSheet(UserInfo.buildings);
                },
                child: Container(
                  padding: EdgeInsets.only(left: 20, right: 20),
                  margin: EdgeInsets.only(top: 30),
                  // width: 600,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    mainAxisSize: MainAxisSize.min,
                    children: [
                      Text(
                        _buildName,
                        style: TextStyle(fontSize: 15),
                      ),
//                      Icon(Icons.keyboard_arrow_right)
                    ],
                  ),
                ),
              ),
              GestureDetector(
                onTap: () {
//                  NavigatorUtil.push(context, PageTraceRecord());
                },
                child: Container(
                  padding: EdgeInsets.only(left: 20, right: 20),
                  margin: EdgeInsets.only(top: 30),
                  width: 600,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        "版本",
                        style: TextStyle(fontSize: 15),
                      ),
                      Text(_versionName)
                    ],
                  ),
                ),
              ),
            ]),
            Positioned(
                bottom: 0,
                child: GestureDetector(
                  onTap: () {
                    showAlertDialog(context);
//                NavigatorUtil.push(context, PageTraceRecord());
//                    logout();
                  },
                  child: Container(
                    color: Colors.white,
                    width: 304,
                    height: 50,
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text("退出登录",
                            style: TextStyle(
                                color: Color.fromRGBO(255, 59, 48, 1)))
                      ],
                    ),
                  ),
                ))
          ],
        ),
      ));

  logout() async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        UserHttpUrl.logout,
        params,
        NetListenerImpl((response) {
          setState(() {
            if (response != null && response.data != null) {
              _summaryTimer?.cancel();
              SharedPreferenceHelp.remove(SPKey.KEY_PASSWORD);
              Navigator.pushAndRemoveUntil(
                context,
                new MaterialPageRoute(builder: (context) => LoginPage()),
                (route) => route == null,
              );
            }
          });
        }, (errorRes) {
          if (errorRes != null) {
            ToastUtil.showToast(errorRes.msg);
          }
        }),
        loadingTip: "正在登出...");
  }

  initCacheLoginInfo() {
    SharedPreferenceHelp.read(SPKey.KEY_ACCOUNT).then((account) {
      setState(() {
        _accountName = account;
      });
    });
  }

  initCacheBuildInfo() {
    SharedPreferenceHelp.read(SPKey.KEY_BUILD_NAME).then((buildName) {
      setState(() {
        _buildName = buildName;
      });
    });
  }

  Future getVersionName() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    print("version${packageInfo.version}");
    setState(() {
      _versionCode = packageInfo.buildNumber;
      _versionName = 'v${packageInfo.version}';
    });
  }

  showAlertDialog(BuildContext context) {
    //设置按钮
    Widget cancelButton = FlatButton(
      child: Text("取消"),
      onPressed: () {
        Navigator.of(context).pop();
      },
    );
    Widget okButton = FlatButton(
      child: Text("确定"),
      onPressed: () {
        Navigator.of(context).pop();
        logout();
      },
    );

    //设置对话框
    AlertDialog alert = AlertDialog(
      content: Text("请确认是否退出当前账号?"),
      actions: [
        cancelButton,
        okButton,
      ],
    );

    //显示对话框
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return alert;
      },
    );
  }

  showBottomSheet(List<Building> buildings) {
    showModalBottomSheet(
      shape: RoundedRectangleBorder(
        borderRadius: BorderRadius.vertical(top: Radius.elliptical(10, 8)),
      ),
      context: context,
      builder: (context) => Container(
          height: (120 + buildings.length * 50.0 + 100),
          child: Column(
            children: [
              Container(
                  decoration: BoxDecoration(
                    color: Colors.white,
                    borderRadius:
                        BorderRadius.vertical(top: Radius.elliptical(10, 8)),
                  ),
                  margin: EdgeInsets.fromLTRB(0, 0, 0, 5),
                  padding: EdgeInsets.symmetric(vertical: 15),
                  child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Text(
                          '请选择建筑',
                          style: TextStyle(fontSize: 15, color: Colors.grey),
                        ),
                      ])),
              Expanded(
                  child: ListView.separated(
//            shrinkWrap: true,
//            physics: new NeverScrollableScrollPhysics(),
                      separatorBuilder: (BuildContext context, int index) =>
                          Divider(height: 0.5),
                      itemCount: buildings.length,
                      itemBuilder: (context, index) {
                        return _item(buildings[index]);
                      })),
              GestureDetector(
                onTap: () {
                  Navigator.of(context).pop();
                },
                child: Container(
                    color: Colors.white,
                    margin: EdgeInsets.fromLTRB(0, 10, 0, 8),
                    padding: EdgeInsets.symmetric(vertical: 10),
                    child: Row(
                      mainAxisAlignment: MainAxisAlignment.center,
                      mainAxisSize: MainAxisSize.max,
                      children: [
                        Text(
                          '取消',
                          style: TextStyle(fontSize: 20),
                        ),
                      ],
                    )),
              )
            ],
          )),
    );
  }

  _item(Building building) {
    return GestureDetector(
      onTap: () {
        try {
          DioHttpClient.addHeader("buildId", building.buildId);
          chooseBuilding(building);
        } on Exception catch (e) {
          print('捕获异常' + e.toString());
        }
      },
      child: Container(
        height: 50,
        color: Colors.white,
        alignment: Alignment.center,
        child: Text(building.buildName),
      ),
    );
  }

  timerRunnable() {
    _summaryTimer =
        Timer.periodic(Duration(milliseconds: 1000 * summaryInterval), (timer) {
      _handleRefresh();
    });
  }

  chooseBuilding(Building building) async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestPost(
        context,
        '${UserHttpUrl.CHOOSE_BUILDING_URL}?buildId=${building.buildId}',
        params,
        NetListenerImpl((response) {
          setState(() {
            if (response != null && response.data != null) {
              Map<String, String> buildInfo = {};
              buildInfo[SPKey.KEY_BUILD_ID] = building.buildId;
              buildInfo[SPKey.KEY_BUILD_NAME] = building.buildName;
              SharedPreferenceHelp.save(buildInfo);
              getLicense(building.buildId);
              areaInfoKey.currentState.showLoading();
              Navigator.pushAndRemoveUntil(
                context,
                new MaterialPageRoute(builder: (context) => Home()),
                (route) => route == null,
              );
            }
          });
        }, (CommonRes errorRes) {
          if (errorRes != null) {
            ToastUtil.showToast(errorRes.msg ?? "请求异常");
          }
        }),
        loadingTip: "请求中...");
  }

  //拷贝的登陆页的 有空 封装一下 避免重复代码
  getLicense(String buildId) async {
    Map<String, dynamic> params = {};
    await DioHttpClient.requestGet(
        context,
        '${UserHttpUrl.GET_LICENCE}?buildId=$buildId',
        params,
        NetListenerImpl((response) {
          if (response != null && response.data != null) {
            ResLicenseInfo res = ResLicenseInfo.fromJson(response.data);
            if (res != null && res.data != null) {
              List<ModuleInfo> modules = res.data.modules;
              if (modules != null) {
                debugPrint('modules的size${modules.length}');
                UserInfo.moduleInfos = modules;
                ModuleInfo info =
                    modules.firstWhere((element) => element.name == '车辆管理');
                if (info != null && info.valid) {
                  print("有效");
                } else {
                  print("无效");
                }
              }
            }
          }
        }, (CommonRes errorRes) {
          if (errorRes != null) {}
        }));
  }
}
